import React, { useState } from 'react'
import Stats from 'stats.js'

import { mock } from './mock'

import './index.less'

function run(callback, frame) {
  let animateId = null
  let preTimestamp = 0

  const maxTime = Number.isFinite(frame) ? 1000 / frame : null

  function animate(timestamp) {
    animateId = requestAnimationFrame(animate)

    if (preTimestamp) {
      const t = timestamp - preTimestamp

      if (maxTime && t < maxTime) return

      callback(t)
    }

    preTimestamp = timestamp
  }

  animate()

  return () => {
    cancelAnimationFrame(animateId)
  }
}

function RenderPage() {
  const [texts, setTexts] = useState([])
  React.useEffect(() => {
    const stats = new Stats()
    stats.showPanel(0)
    document.body.appendChild(stats.dom)

    run(() => {
      stats.begin()

      const list = []
      while (list.length < 10) {
        list.push(mock())
      }
      setTexts(list)

      stats.end()
    })
  }, [])

  return pug`
    div
      each item, index in texts
        .text #{item}
  `
}

export default RenderPage
